﻿using System;

namespace Wisdom.Core.WcfExtensions
{
    /// <summary>
    /// 服务代理工厂类
    /// </summary>
    public class ServiceProxyFactory
    {
        private static EndpointNameGenerator _endpointNameGenerator = new EndpointNameGenerator();

        /// <summary>
        /// 根据传入的终结点名称生成器初始化服务代理工厂
        /// </summary> 
        /// <param name="defaultEndpointNameGenerator"></param>
        public static void Initialize(EndpointNameGenerator defaultEndpointNameGenerator)
        {
            _endpointNameGenerator = defaultEndpointNameGenerator;
        }

        /// <summary>
        /// 根据传入的终结点名称，服务契约接口，创建服务代理
        /// </summary>
        /// <param name="endpointName">终结点名称</param>
        /// <typeparam name="TServiceContract">服务契约接口</typeparam>
        /// <returns>返回服务契约接口的服务代理</returns>
        /// <exception cref="ArgumentNullException">传入的终结点名称为空则抛出异常</exception>
        public static TServiceContract Create<TServiceContract>(string endpointName)
        {
            if (string.IsNullOrEmpty(endpointName))
            {
                throw new ArgumentNullException("endpointName");
            }
            return (TServiceContract)(new ServiceRealProxy<TServiceContract>(endpointName).GetTransparentProxy());
        }

        /// <summary>
        /// 根据传入的服务契约接口创建服务代理
        /// </summary>
        /// <typeparam name="TServiceContract">服务契约接口</typeparam>
        /// <returns>返回服务契约接口的服务代理</returns>
        public static TServiceContract Create<TServiceContract>()
        {
            var endpointName = _endpointNameGenerator.GetEndPointName<TServiceContract>();
            return Create<TServiceContract>(endpointName);
        }
    }
}